//
//  PlayMusic.m
//  MusicPlayer
//
//  Created by xalo on 16/6/18.
//  Copyright © 2016年 朱旭东. All rights reserved.
//

#import "PlayMusic.h"


@interface PlayMusic ()
@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)NSTimer *timer;
@end
@implementation PlayMusic
- (NSTimer *)timer{
    
    if (!_timer) {
        _timer = [NSTimer  scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (AVPlayer * )player{
    if (!_player) {
        _player = [[AVPlayer  alloc] init];
    }
    return _player;
}

//单利
+ (instancetype)defaultManager{
    static PlayMusic *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[PlayMusic alloc] init];
    });
    return handle;
}

//准备去播放,用于播放传进来的Url
- (void)prepareToPlayMusicWithUrl:(NSString *)url{
    //网址为空不播放
    if (!url) {
        return;
    }
    //判断当前有没有正在播放的Item
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self  forKeyPath:@"status"];
    }
    
    //创建一个AVPlayerItem
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
  //添加观察者判断item的状态
    [item  addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //体换item的状态
    [self.player replaceCurrentItemWithPlayerItem:item];
    
    //设置观察者，播放完后自动跳到下一首
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playMusicEnd) name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
}

//自动播放下一首
- (void)playMusicEnd{
    if ([self.delegate respondsToSelector:@selector(playToNextMusic)]) {
        [self.delegate playToNextMusic];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
}

//观察者事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //得到改变后的状态 三种状态
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"未知错误");
            break;
        case AVPlayerItemStatusReadyToPlay:
            NSLog(@"准备播放");
            [self playMusic];
            break;
        case AVPlayerItemStatusFailed:
            NSLog(@"播放失败");
            break;
        default:break;
    }
}
#pragma mark----------------------进度条事件----------------------------
//获取当前的播放的时间
- (NSInteger)fetchCurrentTime{
    CMTime time = self.player.currentItem.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}

//获取总时长
- (NSInteger)fetchTotalTime{
    CMTime time = self.player.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value/time.timescale;
}

//获取当前播放进度
- (CGFloat)fetchprogressValue{
    return [self fetchCurrentTime]/(float)[self fetchTotalTime];
}

//转化格式：00:00时间格式
- (NSString *)changeSecondsTime:(NSInteger)time{
    NSInteger min = time/60;
    NSInteger seconde = time%60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld",min,seconde];
}
// 快进快退
- (void)playMusicWithSliderValue:(CGFloat)progress{
    [self  pasuemusic]; //滑动之前先暂停音乐
    [self.player  seekToTime:CMTimeMake([self  fetchTotalTime]*progress , 1) completionHandler:^(BOOL finished) {
        if (finished) {
            [self  playMusic];
        }
    }];
}


//开始播放
-(void)playMusic{
        [self.player  play];
    //开启定时器
        [self.timer  fire];
}

//暂停
- (void)pasuemusic{
    [self.player  pause];
  //关闭定时器
    [self.timer  invalidate];
    self.timer = nil;
}

//是否正在播放
- (BOOL)isPlaying{
    if (self.player.rate == 0) {
        return NO;
    }else{
        return YES;
    }
}

//定时器方法
- (void)timerAction{//代理实现了协议方法
    if ([self.delegate  respondsToSelector:@selector(playManagerDelegateFetToTime:currenttime:progress:)]) {
        NSString *totalTime = [self changeSecondsTime:[self fetchTotalTime]];
        NSString  *currentTime =  [self changeSecondsTime:[self fetchCurrentTime]];
        CGFloat progress = [self  fetchprogressValue];
        
        [self.delegate playManagerDelegateFetToTime:totalTime currenttime:currentTime progress:progress];
    }
}

















@end
